#!/bin/bash

##################################################
# Simplest wrapper. This wrapper works with the Video Station´s Transcoding Profiles and always will be using MP3 2.0 96kbps or 128kbps when transcoding.
# It derives all parameters to the SynoCommunity´s ffmpeg.

rev="AME_S_2.3"
# Changes:
# AME_S_1.0: Initial release of the simplest wrapper. Fork from AlexPresso. (Deprecated, migrate to AME_S_1.1)
# AME_S_1.1: Correcting the log file. (Deprecated, migrate to AME_S_1.2)
# AME_S_1.2: Improved the viewing of logs. (Deprecated, migrate to AME_S_1.3)
# AME_S_1.3: Fixed a bug that doesn't remove the stderr file due a misconfiguration. (Deprecated, migrate to AME_S_2.1)
# AME_S_2.1: Added support for FFMPEG 6.X binaries and deprecate the FFMPEG 4.X. (Deprecated, migrate to AME_S_2.2)
# AME_S_2.2: Added support for GStreamer libraries. (Deprecated, migrate to AME_S_2.3)
# AME_S_2.3: Homogenize the closing of processes with the Advanced Wrapper, to correct a bug carried over from Alex's code.

##################################################
# VARIABLES
WHITE="\u001B[37m"
RED="\u001b[31m"
BLUE="\u001b[36m"
PURPLE="\u001B[35m"
GREEN="\u001b[32m"
YELLOW="\u001b[33m"
pid=$$
streamid="FFM$pid"
stderrfile="/tmp/ffmpeg-${streamid}.stderr"
logfile="/tmp/wrapper_ffmpeg.log"
errcode=0
arch=`uname -a | sed 's/.*synology_//' | cut -d '_' -f 1`
nas=`uname -a | sed 's/.*synology_//' | cut -d '_' -f 2`
bin1=/var/packages/ffmpeg6/target/bin/ffmpeg

##################################################
# FUNCIONES

function log() {
  echo -e "${WHITE}[$(date '+%Y-%m-%d %H:%M:%S')] [$1] $2" >> $logfile
}
function newline() {
  echo "" >> $logfile
}
function info() {
  log "${BLUE}INFO" "${WHITE}$1"
}

function handle_error() {
  log "${RED}ERROR" "${RED}An error occurred, here is the $stderrfile content:${WHITE}"
  newline
  cat "$stderrfile" >> $logfile
  newline
  errcode=1
  endprocess
}

function _term() {
  info "${PURPLE}========================================[END FFmpeg $pid]${WHITE}"
  newline
  rm -f "$stderrfile"
  kill -TERM "$childpid" 2>/dev/null
  exit $errcode
}
#########################
# EJECUCION

trap _term SIGTERM
trap handle_error ERR

# export LD_LIBRARY_PATH=/var/packages/VideoStation/target/lib/patch/lib/
# export GST_PLUGIN_PATH=/var/packages/VideoStation/target/lib/patch/plugins/

newline
info "${PURPLE}*** PROCESS START REV $rev DS$nas ($arch) PID $pid ***"
info "${PURPLE}========================================[START FFmpeg $pid]${WHITE}"
info "${BLUE}BINARY   = $bin1${WHITE}"
info "${BLUE}DEFAULT_ARGS: $*${WHITE}"

$bin1 "$@" 2> $stderrfile

childpid=$!
wait $childpid

_term
